<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="文章名称">
                <a-input v-model="queryParam.search_key" placeholder="请输入文章名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator flex-y-center flex-x-sb">
        <a-radio-group :value="1">
          <a-radio-button :value="1"> 全部 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">添加</a-button>
          <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
            <a-button > 批量删除 </a-button>
          </a-popconfirm>
        </div>
      </div>
      <div v-show="selectedRowKeys.length" class="select-title">
        <a-alert :message="`已选择 ${selectedRowKeys.length} 项`" type="info" show-icon />
      </div>

      <s-table
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该文章吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>

      <a-modal
        :title="isNew ? '创建文章' : '编辑文章'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文章名称" hasFeedback>
            <a-input
              placeholder="文章名称"
              v-decorator="['name', { rules: [{ required: true, message: '请填写文章名称' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序" hasFeedback>
            <a-input
              placeholder="排序"
              v-decorator="['sort', { rules: [{ required: true, message: '请填写排序' }], initialValue: 0 }]"
            />
            <!-- , { rules: [{required: true, message: '请填写排序'}] , initialValue: 0} -->
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文章详情">
            <WangEditor ref="editor" :value="desc" @change="onDescChange"></WangEditor>
            <a-textarea
              :hidden="true"
              v-decorator="['desc', { rules: [{ required: true, message: '请输入文章详情' }] }]"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable, WangEditor } from '@/components'
import { createAboutArticle, getAboutArticle, editAboutArticle, delAboutArticle, articleBatchDels } from '@/api/content'

const STATUS = {
  1: '显示',
  0: '不显'
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '标题',
    dataIndex: 'name'
  },
  //   {
  //   title: '类别',
  //   dataIndex: 'name',
  // },
  {
    title: '排序',
    dataIndex: 'sort',
    sorter: (a, b) => a.sort - b.sort
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    sorter: (a, b) => a.created_at - b.created_at
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'ProjectList',
  components: {
    STable,
    WangEditor
  },
  data () {
    return {
      selectedRowKeys: [],
      tabIndex: 1,
      isNew: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: { key: '1', label: '显示' },
      // 查询条件参数
      queryParam: {
        search_key: null,
        search_is_show: null
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        console.log(parameter);
        return getAboutArticle(parameter).then((res) => {
          console.log('getAboutArticle', res)
          return res.data
        })
      },
      desc: ''
    }
  },
  filters: {
    statusFilter (key) {
      return STATUS[key]
    }
  },
  created () {},
  methods: {
    onSelectChange (val) {
      this.selectedRowKeys = val
      console.log(val)
    },
    onDescChange (content) {
      console.log('🚀 ~ file: aboutArticleList.vue ~ line 168 ~ content', content)
      this.form.setFieldsValue({
        desc: content
      })
    },
    handleEdit (record) {
      this.desc = ''
      this.isNew = false
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['sort', 'name', 'id']))
        this.desc = record.desc
      })
    },
    resetQueryParams () {
      Object.assign(this.queryParam, {
        search_key: null,
        search_is_show: null
      })
      this.$refs.table.refresh(true)
    },
    handleOk (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        this.modalLoading = true
        if (this.isNew) {
          createAboutArticle(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg
                })
              } else {
                this.$message.success('文章创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          editAboutArticle(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg
                })
              } else {
                this.$message.success('文章编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.defaultCheckedKeys = []
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      delAboutArticle({
        key: record.id
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('文章删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          hide()
        })
    },
    async handleMenuClick () {
      if (!this.selectedRowKeys.length) return

      try {
          const res = await articleBatchDels({ id: this.selectedRowKeys, status: 1 })
          if (res.code != 0) throw res
          this.selectedRowKeys = []
          this.$refs.table.refresh()
          this.$message.success(res.msg)
      } catch (res) {
        this.$message.error(res.msg || '服务器出错')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
